package com.ly.lypopupwindowdemo.activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.menu.MenuPopupHelper;
import android.support.v7.widget.PopupMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;

import com.ly.lypopupwindowdemo.R;

import java.lang.reflect.Field;

public class PopupMenuActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_popup_menu);
    }

    private int checkedItemId = R.id.add;

    public void showPopupMenu(View view) throws IllegalAccessException {
        //show PopupMenu
        PopupMenu popupMenu = new PopupMenu(this,view);
        popupMenu.inflate(R.menu.popup_menu);

        //默认PopupMenu不显示条目的icon,即使我们在menu里面设置了，可以通过反射来强制设置使它显示
        Field field = null;
        try {
            field = popupMenu.getClass().getDeclaredField("mPopup");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        field.setAccessible(true);
        MenuPopupHelper mHelper = (MenuPopupHelper) field.get(popupMenu);
        mHelper.setForceShowIcon(true);

        //设置选中
        popupMenu.getMenu().findItem(checkedItemId).setChecked(true);

        popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                //点击条目，点击后会自动消失
                switch (item.getItemId()){
                    case R.id.add:
                        checkedItemId = R.id.add;
                        Toast.makeText(PopupMenuActivity.this, "选择add", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.share:
                        checkedItemId = R.id.share;
                        Toast.makeText(PopupMenuActivity.this, "选择share", Toast.LENGTH_SHORT).show();
                        break;
                    case R.id.set:
                        checkedItemId = R.id.set;
                        Toast.makeText(PopupMenuActivity.this, "选择set", Toast.LENGTH_SHORT).show();
                        break;
                }

                return false;
            }
        });

        popupMenu.show();
    }
}
